#include <iostream>
#include <string>
#include <ctime>
#include <unistd.h>
#include "socket.hpp"
#include "Protocol.hpp"
using namespace socket_ns;
int main(int argc, char *argv[])
{
    if (argc < 3)
    {
        std::cerr << "Usage:" << argv[0] << "Server_ip Server_port" << std::endl;
        exit(0);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    //构建连接
    SockSPtr sock = std::make_shared<TcpSocket>();
    int n = sock->BuildClientSocket(serverip, serverport);
    if (n < 0)
    {
        std::cerr << "connect error" << std::endl;
        exit(1);
    }

    srand(time(nullptr) ^ getpid());
    const std::string opers = "+-*/";
    while (true)
    {
        int x = rand() % 10;
        usleep(x * 1000);
        int y = rand() % 10;
        usleep(x * y * 1000);
        char oper=opers[rand()%opers.size()];
        
        //1.构建请求
        auto req = Factory::BuildRequestDefault();
        req->set_value(x,y,oper);
        //2.序列化
        std::string jsonstr;
        req->Serialize(&jsonstr);
        std::cout<<"jsonstr: "<<jsonstr<<std::endl;
        //3.添加报头
        jsonstr=Encode(jsonstr);
        std::cout<<"Encode jsonstr: "<<jsonstr<<std::endl;
        //4.发送
        sock->Send(jsonstr);
        
        std::string packagestreamqueue;
        while (true)
        {
            // 5. 读取应答，response
            ssize_t n = sock->Recv(&packagestreamqueue);
            if (n <= 0)
            {
                break;
            }
            std::cout<<packagestreamqueue<<std::endl;
            // 6. 报文解析，提取报头和有效载荷
            std::string package = Decode(packagestreamqueue);
            if (package.empty())
                continue;

            std::cout << "package: \n" << package << std::endl;
            
            // 6. 反序列化
            auto resp = Factory::BuildResponseDefault();
            resp->DeSerialize(package);

            // 7. 打印结果
            resp->PrintResult();
            break;
        }

        sleep(1);
        // break;
    }
    sock->Close();
    return 0;
}